<template>
  <el-card>
    <el-tag type="success">分切材料尺寸</el-tag>
    <br/>
    <el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag)">
      {{tag}}
    </el-tag>
    <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
        @keyup.enter.native="handleInputConfirm" @change="handleInputConfirm">
    </el-input>
    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新尺寸</el-button>
  </el-card>
</template>

<script>
export default {
  name: 'MetManagement',
  data () {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
    }
  },
  mounted () {
    this.getTemplateValue(2)
  },
  methods: {
    async getTemplateValue (k) {
      const res = await this.$http.post('/costOfferTemplateValue/getTemplateValue', {templateId: k})
      this.dynamicTags = JSON.parse(res.data.info.templateValue.templateValue)
    },
    async handleClose (tag) {
      let temp = this.dynamicTags.slice(0, this.dynamicTags.length)
      temp.splice(temp.indexOf(tag), 1)
      let postParam = {id: 2, templateValue: temp}
      const res = await this.$http.post('/costOfferTemplateValue/updateTemplateValue', postParam)
      if (res.data.info) {
        this.getTemplateValue(2)
        this.$message.success('更新数据成功!')
      } else {
        this.$message.error('更新数据失败!')
      }
    },

    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    async handleInputConfirm () {
      let inputValue = this.inputValue
      let temp = this.dynamicTags.slice(0, this.dynamicTags.length)
      if (inputValue) {
        temp.push(inputValue)
        let postParam = {id: 2, templateValue: temp}
        let res = await this.$http.post('/costOfferTemplateValue/updateTemplateValue', postParam)
        if (res.data.info) {
          this.getTemplateValue(2)
          this.$message.success('更新成功')
        } else {
          this.$message.error('更新数据失败!')
        }
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style scoped>
.el-tag{
  margin-right: 10px;
  margin-top: 10px;
}
.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  vertical-align: bottom;
}
</style>
